/***
 *  库存管理
 *     1.  库存查询
 *     2. 入库操作
 *     3. 出库操作
 * */

var stockDAO = require('../dao/balance')
var stockInDAO = require('../dao/stock_in');
var stockInDetailDAO = require('../dao/stock_in_detail');
var stockOutDAO = require('../dao/stock_out');
var stockOutDetailDAO = require('../dao/stock_out_detail');


function queryForBalance(callback) {
    stockDAO.selectAll(callback);
}

function stockIn(stock_in, callback) {
    stockInDAO.insert(stock_in, function (result) { // step1: 添加入库单主单
        if (result.result.insertId) {
            for (var i = 0; i < stock_in.details.length; i++) { //step2: 循环添加入库单详单
                stock_in.details[i].stock_in_id = result.insertId;
                stockInDetailDAO.insert(stock_in.details[i], function (result) {/step2: 循环添加入库单详单
                    stockDAO.selectByProductId(stock_in.details[i].product_id,function (balance) { // 3.查询库存
                           balance.quantity += stock_in.details[i].quantity; // 4,修改库存数量
                           stockDAO.update(balance); // 5.修改库存信息
                    })
                })
            }
        }
    })

    callback({
        flag:true
    })
}

module.exports = {
    queryForBalance,
    stockIn
}